<template>
  <view class="order-page">
    <!-- 状态筛选栏 -->
    <scroll-view scroll-x class="status-filter">
      <view
        v-for="status in statusFilters"
        :key="status.value"
        class="filter-item"
        :class="{ active: activeStatus === status.value }"
        @click="changeStatus(status.value)"
      >
        {{ status.label }}
      </view>
    </scroll-view>

    <!-- 订单列表 -->
    <scroll-view scroll-y class="order-list">
      <!-- 空状态 -->
      <view v-if="orders.length === 0" class="empty-state">
        <image src="/static/images/empty-order.png" mode="aspectFit" />
        <text class="empty-text">暂无订单</text>
        <button class="primary-btn" @click="goToOrdering">去点餐</button>
      </view>

      <!-- 订单卡片 -->
      <view
        v-for="(order, index) in orders"
        :key="index"
        class="order-card"
        @click="showOrderDetail(order)"
      >
        <view class="card-header">
          <text class="shop-name"> 夏日冰城</text>
          <text class="order-status" :class="order.status">{{
            getStatusText(order.status)
          }}</text>
        </view>
        <!-- 订单预览 -->
        <view class="goods-preview">
          <view
            v-for="(item, idx) in order.goodsData.slice(0, 2)"
            :key="idx"
            class="preview-item"
          >
            <image :src="item.image" mode="aspectFill" />
            <text class="goods-name">{{ item.name }}</text>
            <!-- 商品数量, 大于2个商品显示“+X” -->
            <text class="goods-quantity">×{{ item.count }}</text>
          </view>
          <text v-if="order.goodsData.length > 2" class="more-goods"
            >等共有{{ totalCount(order.goodsData) }}件商品</text
          >
        </view>
        <!-- 订单时间戳 -->
        <view class="card-footer">
          <text class="order-time">{{ formatTime(order.OrderNumber) }}</text>
          <text class="order-amount">¥{{ totalPrice(order.goodsData) }}</text>
        </view>
        <!-- 订单操作项 如：取消订单, 再来一单, 删除 -->
        <view class="action-buttons">
          <button
            v-if="order.status === 'unpaid'"
            class="action-btn primary"
            @click.stop="payOrder(order)"
          >
            去支付
          </button>
          <button
            v-if="order.status === 'paid'"
            class="action-btn"
            @click.stop="cancelOrder(order)"
          >
            取消订单
          </button>
          <button
            v-if="order.status === 'completed'"
            class="action-btn"
            @click.stop="reorder(order)"
          >
            再来一单
          </button>
          <button class="action-btn" @click.stop="deleteOrder(index)">
            删除
          </button>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="loadingMore" class="loading-more">
        <text>加载中...</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUpdated } from "vue";
import { formatTime } from "@/utils/formatTime.js";
import { useBillStore } from "@/store/bill";
import { storeToRefs } from "pinia";
const billStore = useBillStore();
//订单数据
const { billData } = storeToRefs(billStore);

// 订单状态筛选
const statusFilters = [
  { label: "全部", value: "all" },
  { label: "待支付", value: "unpaid" },
  { label: "已支付", value: "paid" },
  { label: "已完成", value: "completed" },
  { label: "已取消", value: "cancelled" },
];

const activeStatus = ref("all");
const orders = ref([]);
const currentOrder = ref({});
const showDetail = ref(false);
const refreshing = ref(false);
const loadingMore = ref(false);
const page = ref(1);
const hasMore = ref(true);

// 获取订单列表
const fetchOrders = async (reset = false) => {
  if (reset) {
    page.value = 1;
    hasMore.value = true;
    refreshing.value = true;
  } else {
    loadingMore.value = true;
  }

  try {
    // 直接使用 billData 中的数据
    if (billData.value) {
      orders.value = billData.value;
    } else {
      // 如果 billData 为空，则使用模拟数据
      const mockOrders = generateMockOrders();
      orders.value = mockOrders;
    }

    hasMore.value = orders.value.length >= 10;
  } catch (error) {
    uni.showToast({
      title: "加载失败",
      icon: "none",
    });
    console.error("Error:", error);
  } finally {
    refreshing.value = false;
    loadingMore.value = false;
  }
};

// 生成模拟订单数据
const generateMockOrders = () => {
  // 实现模拟数据生成逻辑
  return [];
};

// 状态切换
const changeStatus = (status) => {
  activeStatus.value = status;
  if (status === 'all') {
    orders.value = billData.value || [];
  } else {
    orders.value = (billData.value || []).filter(order => order.status === status);
  }
};

// 下拉刷新
const onRefresh = () => {
  fetchOrders(true);
};

// 上拉加载更多
const loadMore = () => {
  if (!hasMore.value || loadingMore.value) return;
  page.value++;
  fetchOrders();
};

// 显示订单详情
const showOrderDetail = (order) => {
  currentOrder.value = order;
  showDetail.value = true;
};

// 隐藏订单详情
const hideOrderDetail = () => {
  showDetail.value = false;
};

// 支付订单
const payOrder = (order) => {
  uni.showLoading({ title: "支付中..." });
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({ title: "支付成功" });
    // 更新订单状态
    order.status = "paid";
  }, 1500);
};

// 取消订单
const cancelOrder = (order) => {
  uni.showModal({
    title: "确认取消",
    content: "确定要取消此订单吗？",
    success: (res) => {
      if (res.confirm) {
        uni.showLoading({ title: "处理中..." });
        setTimeout(() => {
          uni.hideLoading();
          uni.showToast({ title: "已取消订单" });
          // 更新订单状态
          order.status = "cancelled";
        }, 1000);
      }
    },
  });
};

// 再来一单
const reorder = (order) => {
  uni.navigateTo({
    url: "/pages/ordering/index?reorder=" + order.id,
  });
};

// 删除订单
const deleteOrder = (index) => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除此订单吗？",
    success: (res) => {
      if (res.confirm) {
        orders.value.splice(index, 1);
        uni.showToast({ title: "删除成功" });
      }
    },
  });
};

// 去点餐
const goToOrdering = () => {
  uni.switchTab({
    url: "/pages/ordering/index",
  });
};

// 计算数量
const totalCount = (data) => {
  return data.reduce((total, item) => total + item.count, 0);
};

// 计算总价
const totalPrice = (data) => {
  return data.reduce((total, item) => total + item.price * item.count, 0);
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    unpaid: "待支付",
    paid: "已支付",
    completed: "已完成",
    cancelled: "已取消",
  };
  return statusMap[status] || status;
};

onMounted(() => {
  fetchOrders(true);
});
</script>

<style lang="scss">
page {
  height: 100%;
}
.order-page {
  height: 100%;

  display: flex;
  flex-direction: column;
  background-color: #f7f7f7;

  .status-filter {
    white-space: nowrap;
    background-color: #fff;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #eee;

    .filter-item {
      display: inline-block;
      padding: 0 30rpx;
      font-size: 28rpx;
      color: #666;

      &.active {
        color: #007aff;
        font-weight: bold;
      }
    }
  }

  .order-list {
    flex: 1;
    padding: 20rpx;

    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 100rpx;

      image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 30rpx;
      }

      .empty-text {
        font-size: 28rpx;
        color: #999;
        margin-bottom: 40rpx;
      }

      .primary-btn {
        background-color: #007aff;
        color: #fff;
      }
    }

    .order-card {
      background-color: #fff;
      border-radius: 16rpx;
      margin-bottom: 24rpx;
      padding: 32rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

      .card-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 24rpx;

        .shop-name {
          font-size: 34rpx;
          font-weight: bold;
          color: #333;
        }

        .order-status {
          font-size: 28rpx;
          font-weight: 500;

          &.unpaid {
            color: #ff9500;
          }

          &.paid {
            color: #007aff;
          }

          &.completed {
            color: #4cd964;
          }

          &.cancelled {
            color: #999;
          }
        }
      }

      .goods-preview {
        background-color: #f9f9f9;
        border-radius: 8rpx;
        padding: 20rpx;
        margin-bottom: 20rpx;

        .preview-item {
          display: flex;
          align-items: center;
          margin-bottom: 15rpx;

          image {
            width: 80rpx;
            height: 80rpx;
            border-radius: 8rpx;
            margin-right: 15rpx;
          }

          .goods-name {
            flex: 1;
            font-size: 28rpx;
          }

          .goods-quantity {
            font-size: 26rpx;
            color: #999;
          }
        }

        .more-goods {
          display: block;
          text-align: center;
          font-size: 26rpx;
          color: #999;
          padding-top: 10rpx;
        }
      }

      .card-footer {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20rpx;

        .order-time {
          font-size: 26rpx;
          color: #999;
        }

        .order-amount {
          font-size: 28rpx;
          font-weight: bold;
        }
      }

      .action-buttons {
        display: flex;
        justify-content: flex-end;

        .action-btn {
          margin-left: 20rpx;
          padding: 10rpx 28rpx;
          font-size: 28rpx;
          border-radius: 32rpx;
          border: 1rpx solid #ddd;
          background-color: #fff;
          transition: all 0.2s ease;

          &:active {
            transform: scale(0.95);
          }

          &.primary {
            background-color: #007aff;
            color: #fff;
            border-color: #007aff;
          }
        }
      }
    }

    .loading-more {
      text-align: center;
      padding: 20rpx;
      font-size: 26rpx;
      color: #999;
    }
  }
}
</style>
